<template>
  <div class="content">
    <el-scrollbar class="scroll-container" ref="scrollRef" @mouseenter="stopScroll" @mouseleave="startScroll">
      <template v-for="(product, index) in loopedData" :key="index" class="product-item">
        <div class="warn-item">
          <h3>{{ product.name }}</h3>
          <p style="margin-left: 10px">{{ product.description }}</p>
          <p>价格: {{ product.price }} 元</p>
        </div>
      </template>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

interface Product {
  name: string;
  description: string;
  price: number;
}

const products: Product[] = [
  { name: '张珊', description: '购买了西红柿', price: 12.88 },
  { name: '李四', description: '购买了葡萄', price: 39.9 },
  { name: '王五', description: '购买了美滋滋', price: 0 },
  { name: '赵六', description: '购买了奥利给', price: 11 },
  { name: '孙七', description: '购买了好果子', price: 666 },
  { name: '周八', description: '购买了猪肉', price: 25.5 },
  { name: '吴九', description: '购买了鱼肉', price: 35 },
  { name: '郑十', description: '购买了香蕉', price: 20 },
  { name: '钱十一', description: '购买了电视机', price: 998 },
  { name: '陈十二', description: '购买了电动车', price: 2888 },
];

const scrollRef = ref<any>(null)
let timer: any = null
const SCROLL_SPEED = 1 // 每次滚动的像素数，可以根据需要调整
const loopedData = [...products, ...products]; // 克隆数据以实现视觉无缝循环

const startScroll = () => {
  if (timer) {
    cancelAnimationFrame(timer)
  }
  function scroll() {
    // 获取滚动容器
    const container = scrollRef.value.$el.querySelector('.el-scrollbar__wrap')
    // 判断是否已滚动到底部
    if (container.scrollTop >= container.scrollHeight / 2) {
      // 滚动到顶部
      container.scrollTop = 0
    } else {
      // 向下滚动
      container.scrollTop += SCROLL_SPEED
    }
    timer = requestAnimationFrame(scroll)
  }
  scroll();
}

const stopScroll = () => {
  if (timer) {
    console.log('停止了滚动动画！');
    cancelAnimationFrame(timer)
    timer = null
  }
}

onMounted(() => {
  startScroll()
})

defineExpose({
  stopScroll,
});

onUnmounted(() => {
  stopScroll()
})

</script>

<style scoped>
  .content {
    position: absolute;
    display: flex;
    flex-direction: column;
    height: 250px; /* 容器高度必须设置，或者直接设置 scroll-container 的高度 */
    margin-top: 10px;
    padding: 15px 20px;
    background-color: white;
    border-radius: 4px;
  }

  .scroll-container {
    width: 100%;
    height: 250px; /* 你可以根据需要调整高度 */
    padding-right: 15px; /* 防止滚动条遮盖内容 */
    transition: scroll 3s linear; /* 控制滚动的平滑过渡 */
  }

  .product-item {
    margin-bottom: 20px;
    padding: 10px;
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 5px;
  }

  :deep(.el-scrollbar__thumb) {
    background: linear-gradient(180deg, #CBF2FA 0%, #30DCFF 100%);
  }

  .warn-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid lightskyblue;
    padding: 10px 0;

  }

  .warn-item:last-child {
    border-bottom: none;
  }

</style>